import { legacy_createStore as createStore, applyMiddleware } from 'redux'
import logger from 'redux-logger'
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";

const initState = {
    username: "",
    token: "",
    site: "",
    sitename: '',
    checkItemsCache: [], //已选择检测项 缓存
    spotCheckParams: {}, //点检参数 去维修页面使用
}

const reducer = (state = initState, action) => {
    const { type, data } = action
    switch (type) {
        case "CHANGE_USERNAME":
            return {
                ...state,
                username: data
            }
        case "CHANGE_TOKEN":
            return {
                ...state,
                token: data
            }
        case "CHANGE_SITE":
            return {
                ...state,
                site: data
            }
        case "CHANGE_SITE_NAME":
            return {
                ...state,
                sitename: data
            }
        case "ADD_CHECK_CHACE":
            if (state.checkItemsCache.length) {
                let i = state.checkItemsCache.findIndex(el => el['no'] == data['no'])
                if (i < 0) {
                    state.checkItemsCache.push(data)
                } else {
                    state.checkItemsCache.splice(i, 1, data)
                }

            } else {
                state.checkItemsCache.push(data)
            }
            return state
        case "DECREMENT_CHECK_CHACE":
            // let index = state.checkItemsCache.findIndex(el => el['no'] == data['no'])
            // return Object.assign(state, {
            //     checkItemsCache: state.checkItemsCache.splice(index, 1)
            // })
            return {
                ...state,
                checkItemsCache: state.checkItemsCache.filter(el => el['no'] !== data['no'])
            }
        case "CHANGE_SPOT_PARAMS":
            return {
                    ...state,
                    spotCheckParams: data
            }
            // return Object.assign(state, {
            //     spotCheckParams: data
            // })
        default:
            return state
    }
}

const persitConfig = {
    key: "root",
    storage: storage,
    //   blacklist: []
}
const persistReducers = persistReducer(persitConfig, reducer)
const store = createStore(persistReducers, applyMiddleware(logger))  //持久化存储开启此项 bug
// store.subscribe(()=>{
//     console.log('store 变化');
// })
const persistor = persistStore(store);

export { store, persistor }


